import * as React from "react";
import { inject, observer } from "mobx-react";
import { Modal, Tooltip, message, Switch, Menu, Dropdown, Icon } from 'antd';
import { History, Location } from 'history';
import { ColumnProps } from 'antd/lib/table/interface';
import  PublicTable  from '../../../common/PublicTable';
import  HeaderButton  from '../../../common/header-button/HeaderButton';
import  EditModal  from '../../../common/editModal/EditModal';
import  CheckModal  from '../../../common/CheckModal';
import { LoginStore, UserStore, RoleStore, AppStore, HomeStore} from '../../../../store';
import {
  pagedDatasAsync,
  // getByIdAsync,
  upsertAsync,
  deleteAsync,
  batchDeleteAsync,
  batchUpsertAsync,
  activeUser,
  upgradeUser
} from '../../../../basicData/api'
import { getQuerystring, dateFormat } from '../../../../util/util'
import '../../home.less';

interface IProps {
  history: History;
  location: Location;
  children?: AudioContextLatencyCategory;
  loginStore: LoginStore;
  userStore: UserStore;
  roleStore: RoleStore;
  appStore: AppStore;
  homeStore: HomeStore;
}


interface State {
  searchText: string;
  visible: boolean,
  isNew: boolean,
  value: any,
  isNewBind: boolean,
  bindVisible: boolean,
  bindValue: any,
  data: {
    totalCount: number,
    items: any
  },
  plainOptions: any,
  checkModalVisible: boolean,
}

//初始化state
const initialState: State = {
  searchText: '',
  visible: false,
  isNew: false,
  bindVisible: false,
  isNewBind: false,
  bindValue: {},
  value: {},
  data: {
    totalCount: 0,
    items: [],
  },
  plainOptions: [],
  checkModalVisible: false,
};

type IState = Readonly<typeof initialState>;

@inject("loginStore", "userStore", "roleStore", "appStore", "homeStore")
@observer
class Users extends React.Component<IProps, IState> {
  type: string
  state: IState = initialState;

  UNSAFE_componentWillMount() {
    this.props.appStore.onSelectChange([], []);
    this.props.appStore.pageChange(1);
  }

  componentDidMount() {
    this.props.loginStore.getAllCompany();
    this.type = 'User'
    const id = Number(getQuerystring('Id'))
    if(id){
      const param = {
        filter:{
            andFilter: [{
              fkTableName: "",
              field: 'id',
              value: id,
              symbol: 5,
              otherFilter:"",
              linkedSymbol: 10
            }]
          }
        
        }
        this.getData(param)
    } else {
      this.getData({})
    }
  }
  /**
   * 获取列表数据
   * @param type 接口名称
   * @param param 请求数据
   */
  getData = (param: any) => {
    const value = {
      ...param,
      skipCount: (this.props.appStore.currentPage - 1) * 10,
    }
    pagedDatasAsync(this.type, value).then ((res: any) => {
      this.setState({
        data: res.result
      })
      
      this.props.userStore.getUser(res.result.items)
    })
  }

  pageChange = (page: number) => {
    this.getData({
      skipCount: (page - 1) * 10,
    })
  }

  edit = (record: any) => {
    this.setState({
      isNew: false,
      visible: true,
      value: record
    })
  }

  delete = (record: any) => {
    Modal.confirm({
      title: '确认删除',
      content: `确认删除用户：【 ${record.userName} 】？` ,
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        deleteAsync(this.type, record.id).then((res: any) => {
          if(res.success){
            message.success('删除成功')
            this.props.appStore.pageChange(1)
            this.getData({})
          }
        })
      },
    })
    
  }

  deleteBindRole = (value: any) => {
    batchDeleteAsync('UserRoleRelated', value).then((res: any) => {
      if (res.success) {
        message.success('删除用户角色关系成功')
        this.handleCancel();
        this.getData({})
      }
    })
  }

  openCheckModal = (record: any) => {
    const { roles } = record;
    const arr: any[] = [];
    roles.map((item: any) => {
      const obj = {
        value: item.userRoleReleateId,
        label: item.roleName
      }
      arr.push(obj)
    })
    this.setState({
      plainOptions: arr,
      checkModalVisible: true,
    }) 
  }

  handleNew =() => {
    const { allRole, getRole } = this.props.roleStore
    this.setState({
      isNew: true,
      visible: true,
      value: {}
    })
    if(!allRole) {
      pagedDatasAsync('Role', {}).then((res: any) => {
        getRole(res.result.items)
      })
    }
  }

  handleCancel = () => {
    this.setState({
      visible: false,
      checkModalVisible: false,
    });
  }

  bindRole = (data?: any)=> {
    const { allRole, getRole } = this.props.roleStore

    this.setState({
      isNewBind: true,
      bindVisible: true,
      bindValue: {
        userUserName: [data.id] || ''
      }
    });
    if(!allRole) {
      pagedDatasAsync('Role', {}).then((res: any) => {
        getRole(res.result.items)
      })
    }
  }

  handleCancelBind = () => {
    this.setState({
      bindVisible: false,
    });
  }

  handleCreateBind = (values: any) => { 
    const userIdArr = values.userUserName;
    const roleIdArr = values.roleRoleName;
    let arr: any = [];
    userIdArr.forEach((userId: string) => {
      roleIdArr.forEach((roleId: string) => {
        arr.push({ entity: { userId, roleId } })
      })
    })
    batchUpsertAsync('UserRoleRelated', arr).then((res: any) => {
      if(res.success) {
        message.success('编辑成功')
        this.setState({
          bindVisible: false
        })
        this.getData({})
      }
    })
  }

  handleCreate = (values: any) => { 
    const { isNew } = this.state
    upsertAsync(this.type, values).then((res: any) => {
      if(res.success){
        this.getData({})
        if(isNew) {
          this.setState({
            visible: false
          })
          Modal.confirm({
            title: '创建用户成功',
            content: '立即为用户绑定角色？',
            okText: '确定',
            cancelText: '暂不绑定',
            onOk: () => this.bindRole(res.result),
          })
        } else {
          message.success('修改成功')
          this.setState({
            visible: false
          })
        }
      }
    })
  }
  upGrade = (record: any) => {
    if(!record.roles || record.roles.length < 1) {
      message.error('升权前，请先给用户绑定管理员角色')
    } else {
      upgradeUser({id: record.id}).then((res:any) => this.getData({}))
    }
  }
  roleChange = (data: any) => {
    const arr: string[] = [];
    data.map((item: any) => {
      arr.push(item.roleName)
    })
    return arr.join('，')
  }

  render() {
    const { visible, isNew, value, data, isNewBind, bindVisible, bindValue, plainOptions, checkModalVisible } = this.state;
    const { allUser } = this.props.userStore;
    const { allRole, getRole } = this.props.roleStore;
    const { selectedRowIds} = this.props.appStore
    const { isAdmin } = this.props.homeStore

    const more =(record: any) =>  (
      <Menu>
        <Menu.Item key="bind" onClick={() => this.bindRole(record)}>分配角色</Menu.Item>
        <Menu.Item key="cancel" onClick={() => this.openCheckModal(record)}>解除角色</Menu.Item>
        {isAdmin && record.isActive
          && record.userCode !== 'InitUser' && record.subordinateCompany 
          && <Menu.Item onClick={() => this.upGrade(record)}><Tooltip title="仅管理员需要进行升权，清除隶属公司信息"> 升权</Tooltip></Menu.Item>
        }
      </Menu>
    );

    const columns: ColumnProps<Users.IUser>[] = [
      {
        title: '序号',
        key: "index",
        render: (text, record, index) => {
          return (<div>{index + 1}</div>)
        }
      },
      {
      title: '用户编码',
      dataIndex: 'userCode',
      key: 'userCode',
    },
    {
      title: '用户名称',
      dataIndex: 'userName',
      key: 'userName',
    },
    {
      title: '所属公司',
      key: "subordinateCompany",
      render: (text, record: any, index) => {
        return (<div>{record.subordinateCompany
          ? record.subordinateCompany.companyName: '--'}</div>)
      }
    },
    {
      title: '角色',
      key: "roles",
      render: (text, record: any, index) => {
        return (<div>{record.roles.length > 0
          ? this.roleChange(record.roles): '--'}</div>)
      }
    },
    {
      title: '手机号码',
      key: 'telNumber',
      render: (text, record: any, index) => {
        return (<div>{record.telNumber || '--'}</div>)
      }
    },
    {
      title: '邮箱',
      key: 'email',
      render: (text, record: any, index) => {
        return (<div>{record.email || '--'}</div>)
      }
    },
    {
      title: '注册时间',
      key: 'creationTime',
      render: (text, record: any, index) => {
        return (<div>{dateFormat(record.creationTime)}</div>)
      }
    },
    {
      title: '状态',
      width: 100,
      key: 'isActive',
      render: (text, record: any, index) => {
        return (<Tooltip title="点击开关改变用户审批状态">
          <Switch
            checkedChildren="已审批"
            unCheckedChildren="未审批"
            checked={record.isActive}
            onChange={() => {activeUser(record.id).then((res:any) => this.getData({}))}}
          />
        </Tooltip>)
      }
    },
    {
      title: '操作',
      width: 120,
      key: 'operation', 
      render: (text, record: any) => {
        return (
          <div>
            <a onClick={() => this.edit(record)}>编辑   </a>
            <a>
              <Dropdown overlay={more(record)} placement="bottomLeft">
                <span>更多<Icon type="down" /></span>
              </Dropdown>
            </a>
          </div>
        )
      }
    }]

    const buttonConfig = {
      content: {
        isUpsert: false,
        isSearch: true,
        isDelete: true,
        isPlus: false,
        isBind:false,
      },
      columns,
      searchConfig: [
        {
          type: 'input',
          name: '用户编码',
          key: 'userCode',
        },
        {
          type: 'input',
          name: '用户名称',
          key: 'userName',
        },
      ],
      plus: this.handleNew,
      sort: (value: any) => {
        this.getData({sorting: value})
      },
      search: (filter: any)=> {
        this.getData({filter:{andFilter: filter}})
      },
      reset: () => {
        this.getData({})
      }, 
      // bind: () => {
      //   this.setState({
      //     isNewBind: true,
      //     bindVisible: true,
      //     bindValue: {
      //       userUserName: [...selectedRowIds]
      //     }
      //   });
      //   if(!allRole) {
      //     pagedDatasAsync('Role', {}).then((res: any) => {
      //       getRole(res.result.items)
      //     })
      //   }
      // },    
      batchDelete: () => {
        batchDeleteAsync(this.type, selectedRowIds)
        .then((res: any) => {
          if(res.success){
            message.success('删除成功')
            this.props.appStore.pageChange(1)
            this.getData({})
          }
        })
        
      },
    }

    const userAdd = [
      { 
        type: 'input',
        name: '用户编码',
        disabled: true,
        key: 'userCode',
        rule: { required: true, message: '请输入编码' }
      },
      { 
        type: 'input',
        name: '用户名称',
        key: 'userName',
        rule: { required: true, message: '请输入名称' }
      },
      { 
        type: 'input',
        name: '联系方式',
        key: 'telNumber',
        rule: { required: false }
      },
    ]

    const bindConfig = [
      { 
        type: 'select_multi',
        name: '用户',        
        key: 'userUserName',
        options: allUser || [],
        rule: { required: true, message: '请选择' }
      },
      { 
        type: 'select_multi',
        name: '角色',
        key: 'roleRoleName',
        options: allRole || [],
        rule: { required: true, message: '请选择'  }
      },
    ]

    return (
      <div>
        <HeaderButton
          {...buttonConfig}
        />
        <PublicTable
          columns={columns}
          dataSource={data}
          pageChange={this.pageChange}
        />
        <EditModal
          title={isNew ? '新增用户' : '编辑用户'}
          isNew={isNew}
          values={value}
          visible={visible}
          onCancel={this.handleCancel}
          onCreate={this.handleCreate}
          editconfig={userAdd}
        />
        <EditModal
          title={isNewBind ? '新增用户角色关系' : '编辑用户角色关系'}
          isNew={isNewBind}
          values={bindValue}
          visible={bindVisible}
          onCancel={this.handleCancelBind}
          onCreate={this.handleCreateBind}
          editconfig={bindConfig}
        />
        <CheckModal
          plainOptions={plainOptions}
          visible={checkModalVisible}
          title={'请勾选需要删除的角色'}
          onCancel={this.handleCancel}
          onCreate={this.deleteBindRole}
        />
      </div>
      )
  }
}

export default Users
